package com.sunshine.lnuplus.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.KeyEvent
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.callback.LoadQingGuoXueQiListCallBack
import com.sunshine.lnuplus.callback.LoginCallBack
import com.sunshine.lnuplus.internet.LoadQingGuoLesson
import com.sunshine.lnuplus.internet.LoadSuperLesson
import com.sunshine.lnuplus.model.QingGuoUserBean
import com.sunshine.lnuplus.model.QingGuoXueQiBean
import com.sunshine.lnuplus.model.SuperData
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.TagHelper
import com.sunshine.lnuplus.utils.TellMeDialog
import com.sunshine.lnuplus.view.DialogWithView
import com.sunshine.lnuplus.viewModel.LoginViewModel
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_login.*


class SuperLoginActivity : BaseActivity() {

    private lateinit var viewModel: LoginViewModel
    private var chooseTermDialog: AlertDialog? = null
    private var qingGuo: String? = null
    private lateinit var qingGuoXueQiList: List<QingGuoXueQiBean>
    private lateinit var userBean: QingGuoUserBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login_super)
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        initView()
    }

    private fun initView() {
        title = "登录"
        StatusBarUtils.setStatusBarWithColor(this, color)
        if(isNight){
            textView_super.setTextColor(Color.WHITE)
            textView_appname.setTextColor(Color.WHITE)
        }
        qingGuo  = intent.getStringExtra("qingguo")
        if(qingGuo != null) textView_super.text = "青果"
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null, false)
        val loading = DialogWithView.newInstance(view, "正在登录",false, null, null)

        fab_to_login.setOnClickListener {
            when {
                edit_sno.text.toString().isEmpty() -> {
                    tip_sno.error = "请输入正确的账号"
                    tip_sno.isErrorEnabled = true
                }
                edit_password.text.toString().isEmpty() -> {
                    tip_sno.isErrorEnabled = false
                    tip_password.error = "请输入的密码"
                    tip_password.isErrorEnabled = true
                }
                else -> {
                    StatusBarUtils.hideSoftInput(this, fab_to_login)
                    loading.show(supportFragmentManager, "loading")
                    tip_password.isErrorEnabled = false
                    if(qingGuo != null){
                        LoadQingGuoLesson.loadXueQiList(qingGuo!!, edit_sno.text.toString(), edit_password.text.toString(), object :
                            LoadQingGuoXueQiListCallBack {
                            override fun onSuccess(
                                schoolList: List<QingGuoXueQiBean>,
                                userBean: QingGuoUserBean
                            ) {
                                loading.dismiss()
                                qingGuoXueQiList = schoolList
                                this@SuperLoginActivity.userBean = userBean
                                handler.sendEmptyMessage(2)
                            }

                            override fun onFail(string: String) {
                                Looper.prepare()
                                loading.dismiss()
                                Toasty.error(this@SuperLoginActivity, string, Toasty.LENGTH_SHORT).show()
                                Looper.loop()
                            }
                        })
                    }else{
                        LoadSuperLesson().login(edit_sno.text.toString(), edit_password.text.toString(), object : LoginCallBack{
                            override fun onSuccess() {
                                loading.dismiss()
                                handler.sendEmptyMessage(1)
                            }

                            override fun onFail(status: String) {
                                Looper.prepare()
                                loading.dismiss()
                                Toasty.error(this@SuperLoginActivity, status, Toasty.LENGTH_SHORT).show()
                                Looper.loop()
                            }
                        })
                    }
                }
            }
        }

        getToolBar()?.setNavigationOnClickListener {
            setResult(Activity.RESULT_CANCELED)
            supportFinishAfterTransition()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            setResult(Activity.RESULT_CANCELED)
            finish()
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    @SuppressLint("HandlerLeak")
    val handler = object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when(msg.what){
                1 -> {
                    val termList = Array(SuperData.superList.size){""}
                    for(i in 0 until SuperData.superList.size){
                        termList[i] = "${SuperData.superList[i].beginYear}年 第${SuperData.superList[i].term}学期"
                    }
                    val builder = MaterialAlertDialogBuilder(this@SuperLoginActivity)
                    builder.setTitle("请选择导入的学期")
                    builder.setSingleChoiceItems(termList, -1
                    ) { _, which ->
                        LoadSuperLesson().load(which, object : LoginCallBack{
                            override fun onSuccess() {
                                if(intent.getBooleanExtra("test", false)){
                                    TellMeDialog.tellMe(this@SuperLoginActivity, supportFragmentManager, false, SuperData.superLessonList.toString(), null)
                                }else{
                                    viewModel.setMaxCount(SuperData.superList[which].maxCount)
                                    if(SuperData.superList[which].time.isNotEmpty()){
                                        viewModel.setLessonTime(SuperData.superList[which].time)
                                    }
                                    chooseTermDialog!!.dismiss()
                                    viewModel.insertUser("超表用户")
                                    setResult(TagHelper.LOGIN)
                                    SuperData.superLessonList.clear()
                                    SuperData.superList.clear()
                                    finish()
                                }
                            }

                            override fun onFail(status: String) {
                                Looper.prepare()
                                chooseTermDialog!!.dismiss()
                                SuperData.superLessonList.clear()
                                SuperData.superList.clear()

                                Toasty.error(this@SuperLoginActivity, status, Toasty.LENGTH_SHORT).show()
                                Looper.loop()
                            }

                        }, viewModel.repository, this@SuperLoginActivity, supportFragmentManager)
                    }
                    chooseTermDialog = builder.create()
                    chooseTermDialog!!.show()
                }
                2 -> {
                    val termList = Array(qingGuoXueQiList.size){""}
                    for(i in qingGuoXueQiList.indices){
                        termList[i] = qingGuoXueQiList[i].mc
                    }
                    val builder = MaterialAlertDialogBuilder(this@SuperLoginActivity)
                    builder.setTitle("请选择导入的学期")
                    builder.setSingleChoiceItems(termList, -1
                    ) { _, which ->
                        val view = LayoutInflater.from(this@SuperLoginActivity).inflate(R.layout.dialog_loading, null, false)
                        val loading = DialogWithView.newInstance(view, "正在解析",false, null, null)
                        loading.show(this@SuperLoginActivity.supportFragmentManager, "")
                        LoadQingGuoLesson.loadQingGuoLesson(qingGuoXueQiList[which].dm, this@SuperLoginActivity.userBean, object : LoginCallBack{
                            override fun onSuccess() {
                                loading.dismiss()
                                chooseTermDialog!!.dismiss()
                                viewModel.insertUser("青果用户")
                                setResult(TagHelper.LOADSCHOOL)
                                finish()
                            }

                            override fun onFail(status: String) {
                                loading.dismiss()
                                Looper.prepare()
                                chooseTermDialog!!.dismiss()

                                Toasty.error(this@SuperLoginActivity, status, Toasty.LENGTH_SHORT).show()
                                Looper.loop()
                            }

                        }, this@SuperLoginActivity, this@SuperLoginActivity.supportFragmentManager)
                    }
                    chooseTermDialog = builder.create()
                    chooseTermDialog!!.show()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(chooseTermDialog != null){
            chooseTermDialog!!.dismiss()
        }
    }
}
